package com.jintoufs.service.region.impl;

import com.jintoufs.dao.region.RegionMapper;
import com.jintoufs.domain.region.Region;
import com.jintoufs.service.region.RegionService;
import com.jintoufs.util.ztree.TreeNode;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class RegionServiceImpl implements RegionService {

    @Resource
    private RegionMapper regionMapper;

    @Override
    public Region queryById(Short id) {
        return regionMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<TreeNode> getModuleTree(Region entity) {
        List<Region> list = regionMapper.queryZtree();
        List<TreeNode> nodes = new ArrayList<TreeNode>();
        for (Region tmp : list) {
            nodes.add(buildModuleNode(tmp, entity));
        }
        return nodes;
    }


    private TreeNode buildModuleNode(Region entity, Region oldResource) {
        TreeNode areaNode = new TreeNode();
        areaNode.setId(String.valueOf(entity.getId()));
        areaNode.setName(entity.getName());
        if (entity.getParentId() != null && entity.getParentId() != 0) {
            areaNode.setPId(String.valueOf(entity.getParentId()));
        } else {
            areaNode.setIsParent(true); // 处理无子节点的父节点
        }
        if (oldResource != null && oldResource.getId().equals(entity.getId())) {
            areaNode.setChecked(true);
        }
        areaNode.setOpen(false);
        return areaNode;
    }
}
